package com.cloud.spring.demo.controller;

import com.cloud.spring.demo.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Log4j2
@RestController
@RequestMapping("validation")
public class ValidationController {
    @RequestMapping("test1")
    public String createUser(@Validated User user, BindingResult bindingResult) {
        String result = "验证失败";

        if (bindingResult.getErrorCount() == 0) {
            result = "通过验证！";
        }

        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError error : allErrors) {
            String defaultMessage = error.getDefaultMessage();
            log.info(defaultMessage);
        }

        return result;
    }
}
